<?php
/*
 返回：十六进制的随机字符串
 */
function dr_random_alphanum($length)
{
	$string = '';

	while (strlen($string) < $length)
		$string .= str_pad(base_convert(mt_rand(0, 46655), 10, 36), 3, '0', STR_PAD_LEFT);

	return substr($string, 0, $length);
}

/*
 对明文密码进行加密
 返回：加密后的十六进制密码
 */
function dr_db_calc_passcheck($password, $salt)
{
	return sha1(substr($salt, 0, 8) . $password . substr($salt, 8));
}


/*
 * 返回：带中文版本的substr
 */
function dr_utf8_substr($string, $start = 0, $len = 30)
{
	$start_position = strlen($string);
	$end_position = strlen($string);
	$count = 0;
	$start_byte = 0;

	for ($i = 0; $i < strlen($string); $i++)
	{
		if ($count >= $start && $start_position >= $i) {
			$start_position = $i;
			$start_byte = $count;
		}
		if ($count - $start_byte >= $len) {
			$end_position = $i;
			break;
		}

		$value = ord(substr($string, $i, 1));
		if ($value > 127) {
			$count++;
			if ($value >= 192 && $value <= 223) //2字节
				$i++;
			else if ($value >= 224 && $value <= 239) //3字节
				$i = $i + 2;
			else if ($value >= 240 && $value <= 247) //4字节
				$i = $i + 3;
		}
		$count++;
	}
	return substr($string, $start_position, $end_position - $start_position);
}

/*
 * 返回：如果字符串长度大于30，则截取前半部分；否则原样输出
 */
function dr_cut_string($string, $len = 30)
{
	if (strlen($string) <= 30)
		return $string;
	else
	{
		$str = dr_utf8_substr($string, 0, $len);
		$str = $str . '...';
		return $str;
	}
}

/**
 * XXX 根据用户的等级获得用户的角色
 *
 * @param int $user_level
 */
function dr_get_role_with_level($user_level)
{

	return '普通用户';
}

/**
 * 获得数组中指定的值，如果该值没有定义，则返回null
 */
function dr_get_value_with_key($array, $key, $type = null)
{
	if (!isset($array[$key])) {
		switch ($type) {
			case 'int':
			case 'integer':
				return 0;
			case 'string':
				return '';
			case 'bool':
			case 'boolean':
				return false;
			case 'float':
			case 'double':
				return 0.0;
			default:
				return null;
		}
	}
	return $array[$key];
}